package com.intelligent.ispc.web.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * Created by yangli on 2015-07-15.
 */
public class ApplicationUtil {

    public static String getProjectPathSeparator() {
        String result = ApplicationUtil.class.getResource("ApplicationUtil.class").getPath().toString();
        int index = result.indexOf("WEB-INF");
        if (index == -1) {
            index = result.indexOf("bin");
        }
        result = result.substring(0, index);
        if (result.startsWith("file")) {
            result = result.substring(6);
        } else if (result.startsWith("jar")) {
            result = result.substring(10);
        }
        if (result.startsWith(File.separator))
            result = result.substring(1);
        return result;
    }

    public static String getProjectPath() {
        String result = getProjectPathSeparator();
        if (result.endsWith(File.separator))
            result = result.substring(0, result.length() - 1);
        return result;
    }

    public static String getApplicationName() {
        String result = getProjectPath();
        result = result.substring(result.lastIndexOf(File.separator) + 1);
        return result;
    }

    public static String getBasePathNotContainServerName(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        sb.append(request.getScheme());
        sb.append(File.pathSeparator + "//");
        sb.append(request.getServerName());
        sb.append(File.pathSeparator);
        sb.append(request.getServerPort());
        return sb.toString();
    }
}
